package com.young.msg.core;

import com.young.common.util.StringUtils;
import com.young.msg.model.MailSenderConfig;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.nio.charset.StandardCharsets;

/**
 * 邮件发送器
 *
 * @author wangjy
 * @date 2021/10/30 00:42:44
 */
public class YoungJavaMailSender extends JavaMailSenderImpl {

    /**
     * 发送邮箱标识
     */
    private String senderCode;
    /**
     * 发件人名字
     */
    private String fromName;

    /**
     * 创建发送器实例
     *
     * @param mailConfig
     * @return
     */
    public static YoungJavaMailSender newInstance(MailSenderConfig mailConfig) {
        YoungJavaMailSender sender = new YoungJavaMailSender();
        sender.setHost(mailConfig.getMailHost());
        if (mailConfig.getMailPort() != null) {
            sender.setPort(mailConfig.getMailPort());
        }
        sender.setUsername(mailConfig.getUsername());
        sender.setPassword(mailConfig.getPassword());
        sender.setProtocol(mailConfig.getProtocol());
        sender.setDefaultEncoding(StandardCharsets.UTF_8.name());
        sender.senderCode = mailConfig.getSenderCode();
        sender.fromName = mailConfig.getFromName();
        return sender;
    }

    /**
     * 校验发送器是否有效
     *
     * @return
     */
    public boolean check() {
        return StringUtils.isNotBlank(senderCode)
                && StringUtils.isNotBlank(this.getHost())
                && StringUtils.isNotBlank(this.getUsername())
                && StringUtils.isNotBlank(this.getPassword())
                && StringUtils.isNotBlank(this.getProtocol())
                && StringUtils.isNotBlank(this.getDefaultEncoding());
    }

    private YoungJavaMailSender() {
    }

    public String getSenderCode() {
        return senderCode;
    }

    public String getFromName() {
        return fromName;
    }
}
